<template>
  <div class="c-percentnum">
    <template v-if="Number(type) <= typeCount">
      <data-v-chart class="chart" @set-opt="onSet"></data-v-chart>
      <div class="data">
        <div class="name">{{ name }}</div>
        <div class="number">{{ fmtedNum }}</div>
      </div>
    </template>
  </div>
</template>

<script>
import { formatNum } from "../utils";

import chart1 from "./chart1";
import chart2 from "./chart2";
import chart3 from "./chart3";
import chart4 from "./chart4";
import chart5 from "./chart5";
import chart6 from "./chart6";
import chart7 from "./chart7";
import chart8 from "./chart8";
import chart9 from "./chart9";

const chartList = {
  chart1,
  chart2,
  chart3,
  chart4,
  chart5,
  chart6,
  chart7,
  chart8,
  chart9
};

export default {
  name: "data-v-percentnum",
  props: {
    name: {
      type: String,
      default: "默认数据名称"
    },
    value: {
      type: [String, Number],
      default: 0.0001
    },
    number: {
      type: [String, Number],
      default: 0
    },
    type: {
      type: [String, Number],
      default: 1
    }
  },
  data() {
    return {
      operateType: "draw"
    };
  },
  computed: {
    percentage() {
      let value = this.value;
      if (value > 1) {
        value = 1;
      }
      let p = (value * 100).toFixed(2);
      return p;
    },
    fmtedNum() {
      return formatNum(this.number);
    },
    key() {
      let key = "chart" + this.type;
      return key;
    },
    typeCount() {
      return Object.keys(chartList).length;
    }
  },

  watch: {
    name() {
      this.chartOperate("update");
    },
    value() {
      this.chartOperate("update");
    }
  },
  methods: {
    onSet(chart) {
      this.chart = chart;
      this.chartOperate("draw");
    },

    chartOperate(operateType) {
      let { chart, percentage, key } = this;
      let chartObj = chartList[key];

      if (!chartObj) {
        throw new TypeError("类型为 [" + this.type + "] 的图表未定义!");
      }

      if (operateType === "draw") {
        chartObj.draw(chart, percentage);
      } else if (operateType === "update") {
        chartObj.update(percentage);
      }
    }
  }
};
</script>

<style lang="less">
@cyan-color: #04c9fc;

.c-percentnum {
  width: 200px;
  height: 200px;
  display: inline-block;

  .chart {
    width: 150px;
    height: 150px;
    margin: 0 auto;
  }
  .data {
    text-align: center;
  }
  .name {
    opacity: 0.5;
    margin-bottom: 5px;
  }
  .number {
    font-size: 18px;
    color: @cyan-color;
  }
}
</style>
